package com.aliengen.thingple.driverapp.ui.activities;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.aliengen.thingple.cmc168mwithservice.Common;
import com.aliengen.thingple.driverapp.R;
import com.aliengen.thingple.driverapp.data.exception.InvalidTagException;
import com.aliengen.thingple.driverapp.data.local.EventModel;
import com.aliengen.thingple.driverapp.data.models.Anomaly;
import com.aliengen.thingple.driverapp.data.models.CylinderTag;
import com.aliengen.thingple.driverapp.data.models.Report;
import com.aliengen.thingple.driverapp.device.CMCHandler;
import com.aliengen.thingple.driverapp.network.api.ThingpleAPI;
import com.aliengen.thingple.driverapp.network.api.exception.APICallException;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@EActivity(R.layout.activity_anomaly_define)
public class AnomalyDefineActivity extends AbstractBaseActivity {

    @Extra("cylinder_tag")
    protected CylinderTag cylinder;

    @Extra("report")
    protected Report report;

    @ViewById
    protected TextView cylinderReference;

    @ViewById
    protected Spinner inspection_anomaly;

    @ViewById
    protected Button buttonValidate;

    protected AddAnomalyThread thread;

    @AfterViews
    protected void init()
    {
        setTextView(cylinderReference, R.string.cylinder_reference, cylinder.getReference());

        mApplication.getHandler().setOnEventListener(new CMCHandler.OnEventListener() {
            @Override
            public void onPressDown() {
            }

            @Override
            public void onPressUp() {
            }

            @Override
            public void onReceiveData() {
            }

            @Override
            public void onRead(String data) {
            }

            @Override
            public void onReadFailed() {
            }

            @Override
            public void onWrite() {
                Log.i("AnomalyDefineActivity", "onWrite");
                thread.start();
                mApplication.mService.device.unselect();
            }

            @Override
            public void onWriteFailed() {
                Log.i("AnomalyDefineActivity", "onWriteFailed");
                mApplication.mService.device.unselect();
                showToast(R.string.anomaly_define_error);
                buttonValidate.setEnabled(true);
            }

            @Override
            public void onTagSelected() {
                byte[] epc = cylinder.getEpc();
                Log.i("AnomalyDefineActivity", "Preceding EPC: " + Common.arrByte2String(epc, 0, epc.length));

                byte[] data = epc;
                data[5] = (byte) ((data[5] & 0xFF) | 0x01); //TODO: Uncomment before production

                try
                {
                    cylinder = new CylinderTag(data);
                    Log.i("AnomalyDefineActivity", "New EPC: " + Common.arrByte2String(data, 0, data.length));
                    mApplication.mService.device.write(data, 4000);
                } catch(InvalidTagException e)
                {
                    e.printStackTrace();
                    Log.e("AnomalyDefineActivity", "Tag problem!");
                    showToast("Unable to set the new EPC!");
                }
            }

            @Override
            public void onTagSelectFailed() {
                buttonValidate.setEnabled(true);
                showToast("Select function not working! Try to update the firmware!");
            }
        });

    }

    class AddAnomalyThread extends Thread {
        @Override
        public void run() {
            int position = inspection_anomaly.getSelectedItemPosition();
            String[] inspectionString = getResources().getStringArray(R.array.inspection_control_points_slug);
            String controlPointSelected = inspectionString[position];

            Log.i("AddAnomalyThread", "Control point: " + controlPointSelected);

            EventModel event = new EventModel();
            event.huashen_number = AnomalyDefineActivity.this.cylinder.getReference();
            event.operation_id = 10;
            event.cylinder_type = "cylinder";
            event.truck_id = report.truck.getTruckId();
            event.truck_plate_number = report.truck.getPlateNumber();
            event.anomaly_phase = report.operation;
            event.anomaly_inspection = controlPointSelected;
            event.save();

            Anomaly anomaly = new Anomaly(report.operation, controlPointSelected, AnomalyDefineActivity.this.cylinder, report.truck.getTruckId());

            report.anomalies.add(anomaly);
            showToast(R.string.anomaly_defined);
            AnomalyDefineActivity.this.finish();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    buttonValidate.setEnabled(true);
                }
            });
        }
    };

    public void onClickValidate(View view){
        thread = new AddAnomalyThread();
        buttonValidate.setEnabled(false);
        byte[] epc = this.cylinder.getEpc();
        mApplication.mService.device.setPower(28);
        mApplication.mService.device.select(epc, 2000);
    }
}
